package sealte.util.compress;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIP {
	
	/**
	 * 将 字符串 压缩成 字节数组
	 * @param str
	 * @return
	 */
	public static byte[] doCompress(String str, String decoding){
		GZIPOutputStream out = null;
		ByteArrayInputStream in = null;
		ByteArrayOutputStream byteOut = null;
		try{
			byteOut = new ByteArrayOutputStream();
			out = new GZIPOutputStream(byteOut);
			
			in = new ByteArrayInputStream(str.getBytes(decoding));
			
			byte[] buf = new byte[1024];
			int len;
			while((len=in.read(buf))>0){
				out.write(buf,0,len);
			}
			
			out.finish();
			
			return byteOut.toByteArray();
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}finally{
			if(null!=in){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null!=byteOut){
				try {
					byteOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null!=out){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 将 字节数组 解压缩成 字符串
	 * @param byteIn
	 * @return
	 */
	public static String unCompress(byte[] byteIn, String encoding){
		GZIPInputStream in = null;
		ByteArrayInputStream byte_in = null;
		ByteArrayOutputStream byte_out = null;
		try{
			byte_in = new ByteArrayInputStream(byteIn);
			in = new GZIPInputStream(byte_in);
			
			byte_out = new ByteArrayOutputStream();
			
			byte[] buf = new byte[1024];
			int len;
			while((len=in.read(buf))>0){
				byte_out.write(buf,0,len);
			}
			
			return new String(byte_out.toByteArray(),encoding);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}finally{
			if(null!=byte_in){
				try {
					byte_in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null!=byte_out){
				try {
					byte_out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null!=in){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
